var Promise = require('bluebird'),
    Mongoose = require('mongoose'),
    _ = require('lodash'),

    tagModel = require('../models/tag'),
    ideaModel = require('../models/idea'),
    vote = require('../models/vote');

module.exports = {
    createIdea: function (idea, callback) {
        return new Promise(function (resolve, reject) {
            (idea).save(function (err) {
                if (err) {
                    reject(new Error('Unable create new idea.'));
                }
                resolve([]);
            });
        });
    },

    addTags: function (tags) {
        return new Promise(function (resolve, reject) {
            tags.forEach(function (tag) {
                var tag = new tagModel({
                    name: tag
                });

                tag.save(function (err) {
                    if (err) {
                        if (err.code === 11000) {
                            resolve([]);
                        } else {
                            reject(new Error('Unable create new tag.'));
                        }
                    }
                    resolve([]);
                });
            });
        });
    },

    findUserVoteOnIdea: function (user, ideaArray) {
        return new Promise(function (resolve, reject) {
            var ideaList = _.map(ideaArray, function (idea) {
                return new Mongoose.Types.ObjectId(idea._id);
            });
            vote.find({idea: {$in: ideaList}, user: new Mongoose.Types.ObjectId(user)},
                function (err, vote) {
                    if (err || !vote) {
                        // Handle this err
                        return reject(new Error('Something'));
                    } else if (vote) {
                        return resolve(vote);
                    }
                });
        });
    }
};
